# 作者: YYJ
# 2025年07月17日14时37分33秒
# 2486249622@qq.com

import re
from socket import socket, AF_INET, SOCK_STREAM, SOL_SOCKET, SO_REUSEADDR
import select


def service_client(client_socket, request):
    if not request:
        return
    print(request)
    request_lines = request.splitlines()
    print("")
    print(">" * 20)
    print(request_lines)
    if request_lines:
        file_name = ""
        ret = re.match(r"[^/]+(/[^ ] *)", request_lines[0])
        if ret:
            file_name = ret.group(1)
            print("*" * 50, file_name)
            if file_name == "/":
                file_name = "index.html"

        try:
            f = open("./html" + file_name, "rb")
        except:
            response = "HTTP/1.1 404 NOT FOUND\r\n"
            response += "\r\n"
            response += "----file not found----"
            client_socket.send(response.encode("utf-8"))
        else:
            html_content = f.read()
            f.close()
            response = "HTTP/1.1 200 OK\r\n"
            response += "\r\n"
            client_socket.send(response.encode("utf-8"))
            client_socket.send(html_content)

    client_socket.close()


def main():
    tcp_server = socket(AF_INET, SOCK_STREAM)
    tcp_server.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
    tcp_server.bind(('', 7890))
    tcp_server.listen(128)
    tcp_server.setblocking(False)
    epl = select.epoll()
    epl.register(tcp_server.fileno(), select.EPOLLIN)
    fd_event_dict = dict()
    while True:
        fd_event_list = epl.poll()
        for fd, event in fd_event_list:
            if fd == tcp_server.fileno():
                client_socket, client_addr = tcp_server.accept()
                epl.register(client_socket.fileno(), select.EPOLLIN)
                fd_event_dict[client_socket.fileno()] = client_socket
            elif event == select.EPOLLIN:
                recv_data = fd_event_dict[fd].recv(1024).decode("utf-8")
                if recv_data:
                    service_client(fd_event_dict[fd], recv_data)
                else:
                    fd_event_dict[fd].close()
                    epl.unregister(fd)
                    del fd_event_dict[fd]

    tcp_server.close()
